#!/bin/bash 
# http://marius.scurtescu.com/

# Licence : GNU GPL

# Dependency
#		jhead (used if available, can't rotate automatically without it)
#		mogrify (in imagemagick)
#		zenity
# Based on
#		Rotate-Mirror_pictures by yeKcim 
#       http://yeknan.free.fr/blog/index.php?2006/03/12/71-rotate-mirror_pictures-03
#       http://g-scripts.sourceforge.net/cat-multimedia.php#image
#   and
#       ImageTool cteated by Chris Wilson
#       http://blixtra.org/blog/installing-nautilus-scripts/

TITLE="Rotate Image(s)"

if [ $# -eq 0 ] ; then
	zenity --error --title="$TITLE" --text="Please select at least one image."
	exit 2
fi

which mogrify 2>/dev/null
if [ $? != 0 ] ; then
	zenity --error --title="$TITLE" --text="mogrify not found, please install Imagemagick."
	exit 1
fi

ANGLE=`zenity --title "$TITLE" --list --radiolist --column="" --column="Rotation direction" TRUE Clockwise FALSE Counterclockwise FALSE Auto --text "Select rotation angle:" --height "250"`

if  [ $? != 0 ]; then
	exit 0
fi

PROGRESS=0
COUNTER=1

(for i in "$@"
  ##echoed strings starting with "#" are used as text in the the progress window
  ##echoed integers are used as the percentage for the progress bar
  do
    echo $PROGRESS
    
    echo "#Processing image `basename \"${i}\"` ($COUNTER/$#)"
    
    case $ANGLE in
    	Clockwise)
    		mogrify -rotate 90 "$i"
    		;;
    	Counterclockwise)
    		mogrify -rotate 270 "$i"
    		;;
    	Auto)
            which jhead 2>/dev/null
            if [ $? != 0 ] ; then
                zenity --error --title="$TITLE" --text="jhead not found, please install it in order to use auto rotate."
	            exit 1
            fi

    		jhead -autorot "$i"
    		;;
    esac
    
    ((PROGRESS = $COUNTER*100/$#)) 
    ((COUNTER+=1))
  done
  echo 100
  echo "#Done") | zenity --progress --title="$TITLE" --text="Processing image ..." --percentage=${PROGRESS}
